/* $RCSFile: RadPanelMenuNavigation.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/RadPanelMenuNavigation.cs $
 * $log$
 * Revision 19 2011/02/22 01:23:08  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 19 2011/02/22 01:22:18  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using AddonNice.Core;
using AddonNice.Diagnostics;
using AddonNice.Design;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Security;
using AddonNice.Settings;
using Telerik.Web.UI;
using AddonNice.Helpers;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;

namespace AddonNice.UI.WebControls 
{ 

	/// <summary>
	/// RadPanelBarMenu navigation inherits from Menu Webcontrol
	/// and adds the 'glue' to link to tabs tree.
	/// </summary>
	public class RadPanelMenuNavigation : RadPanelBar, INavigation  , IPortalMenu
	{ 
		const string strDefaultskin     =   "defaultskin";
		PortalSettings _portalSettings; 
		PortalSettings portalSettings 
		{
			get 
			{
				if ( _portalSettings == null )
					_portalSettings = (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
				return _portalSettings;
			}
		}

		bool _TrackClientMouse = true;
		/// <summary> 
		/// Should control send items tooltip in status
		/// Default true;
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool TrackClientMouse 
		{ 
			get{return _TrackClientMouse;} 
			set{_TrackClientMouse = value;} 
		} 

		bool _ShowImages = true;
		/// <summary> 
		/// Indicates if control should show the images
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool ShowImages 
		{ 
			get{return _ShowImages;} 
			set{_ShowImages = value;} 
		} 

		bool _FirstImagesOnly = true;
		/// <summary> 
		/// Indicates if control should show the FirstImagesOnly
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool FirstImagesOnly 
		{ 
			get{return _FirstImagesOnly;} 
			set{_FirstImagesOnly = value;} 
		} 

		bool _ImageOnParents = true;
		/// <summary> 
		/// Indicates if control should show images for Parent pages
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool ImageOnParents 
		{ 
			get{return _ImageOnParents;} 
			set{_ImageOnParents = value;} 
		} 

		// Zero means let full image size
		int _ImgWidth  =   0;
		[Category("Data"), PersistenceMode(PersistenceMode.Attribute)] 
		public int ImgWidth
		{
			get
			{
				return _ImgWidth;
			}
			set
			{
				_ImgWidth = value;
			}
		}


		#region INavigation implementation 
		private BindOption _bind = BindOption.BindOptionTop; 
		private int _definedParentTab = -1;

		private bool _useTabNameInUrl = false;

		/// <summary> 
		/// Indicates if control should show the tabname in the url 
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool UseTabNameInUrl 
		{ 
			get{return _useTabNameInUrl;} 
			set{_useTabNameInUrl = value;} 
		} 

		private bool _autoBind = false; 

		/// <summary> 
		/// Indicates if control should bind when loads 
		/// </summary> 
		[ 
			Category("Data"), PersistenceMode(PersistenceMode.Attribute) 
		] 
		public bool AutoBind 
		{ 
			get{return _autoBind;} 
			set{_autoBind = value;} 
		} 

		/// <summary> 
		/// Describes how this control should bind to db data 
		/// </summary> 
		[ 
			Category("Data"), PersistenceMode(PersistenceMode.Attribute) 
		] 
		public BindOption Bind 
		{ 
			get {return _bind;} 
			set 
			{ 
				if(_bind != value) 
				{ 
					_bind = value; 
				} 
			} 
		} 

		/// <summary>
		/// defines the parentPageID when using BindOptionDefinedParent
		/// </summary>
		[
			Category("Data"), PersistenceMode(PersistenceMode.Attribute)
		]
		public int ParentPageID
		{ 
			get {return _definedParentTab;}
			set
			{
				if(_definedParentTab != value)
				{
					_definedParentTab = value;
				}
			}
		}
		#endregion 

		
		bool _HideUnderCrm = true;
		/// <summary> 
		/// Should control be hidden when under Crm 
		/// default: true
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool HideUnderCrm
		{ 
			get{return _HideUnderCrm;} 
			set{_HideUnderCrm = value;} 
		} 

		bool _IsPortalMenus = false;
		/// <summary> 
		/// Should control act as a portal menu
		/// default: false
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool IsPortalMenus 
		{ 
			get{return _IsPortalMenus;} 
			set{_IsPortalMenus = value;} 
		} 
		
		
		#region IPortalMenu implementation
		
		public void ResetCache()
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation ResetCache BEG Items.Count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
			Cache2.RemoveGlobalPagesCacheKey();
		}

		public void Rebind()
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation Rebind BEG Items.Count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
			ClearSelectedItems();
			Items.Clear();
			InitData();
			if (AutoBind)
				DataBind();
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation Rebind END IsPostBack: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
		}
	   
		public bool SelectMenuItem(int wPageId)
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation SelectMenuItem BEG PageId: {0}.", wPageId),NavTraceSwitch.Sw.Info);
			RadPanelItem it =   FindItemByValue(wPageId.ToString());
			bool found      =   ( it != null );
			if ( found )
				it.Selected =   true;
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation SelectMenuItem END found: {0}.", found),NavTraceSwitch.Sw.Info);
			return found;
		}

		public Control AjaxControl
		{
			get
			{
				return this;
			}
		}

		public bool ShouldRegisterInAjaxManager
		{
			get
			{
				return true;
			}
		}

		#endregion IPortalMenu

		public RadPanelMenuNavigation() 
		{ 
			Load                +=  new EventHandler(LoadControl);
		}


		protected override void OnInit(EventArgs e)
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation OnInit BEG IsPostBack: {0}, AutoBind: {1}, ShowImages: {2}", Page.IsPostBack,AutoBind,ShowImages),NavTraceSwitch.Sw.Info);
			if ( !DesignMode )
			{
				InitData();
				// Registers in portal
				if ( IsPortalMenus )
					portalSettings.AddPortalMenu(this);
			}
			base.OnInit(e);
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation OnInit END count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
		}

		private void LoadControl(object sender, EventArgs e) 
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation LoadControl BEG IsPostBack: {0}, AutoBind: {1}, ShowImages: {2}", Page.IsPostBack,AutoBind,ShowImages),NavTraceSwitch.Sw.Info);
			if (AutoBind)
				DataBind();
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation LoadControl END IsPostBack: {0}, item.count: {1}", Page.IsPostBack,Items.Count),NavTraceSwitch.Sw.Info);
		}

		/// <summary>
		/// Do databind.
		/// </summary>
		protected void InitData()
		{
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation InitData BEG IsTrackingViewState: {0}.",IsTrackingViewState),NavTraceSwitch.Sw.Info);
			// Must hide menu under CRM ?
			if ( HideUnderCrm && PortalSettings.IsUnderCRM )
			{
				Visible                                 =   false;
				return;
			}
			// Build list of tabs to be shown to user 
			int CurrentParentPageID                     =   -1;
			AuthorizedPageStripDetail authorizedTabs    =   new AuthorizedPageStripDetail(Bind,ParentPageID,CurrentParentPageID);
			ParentPageID                                =   authorizedTabs.ParentPageID;
			bool isForm                                 =   (Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms );
			IAddonNiceUser    curUser                   =   PortalSettings.CurrentUser;
			bool isAuthenticated                        =   ( curUser != null ) ? !curUser.IsAnonymous : false;
			for (int i = 0; i < authorizedTabs.Count; i++)
			{
				PageStripDetails myPage     =   authorizedTabs[i];
				if (( myPage.OkForMenus ) &&
					( isForm || ( !isForm && !myPage.FormsOnly ) ) &&
					( isAuthenticated || ( !isAuthenticated && !myPage.AuthenticatedOnly ) ) )
					AddMenuItem(myPage);
			}
			if (IsTrackingViewState)
				ClearChildViewState();
			if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture, "[V]RadPanelMenuNavigation InitData END IsTrackingViewState: {0}.", IsTrackingViewState), NavTraceSwitch.Sw.Info);
		} 

		/// <summary>
		/// Extract the image url from skinid and add it to a Panel Item
		/// </summary>
		void SetPanelImageUrl(RadPanelItem mn, string wSkinID,bool smallImg)
		{
			try
			{
				if ( NavTraceSwitch.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation SetPanelImageUrl wSkinID: {0}", wSkinID),NavTraceSwitch.Sw.Info);
				Hashtable skTb          =   portalSettings.GetSkinImageMenu(smallImg);
				bool okSkin             =   (skTb[wSkinID] != null);
				if ( NavTraceSwitch.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation SetPanelImageUrl OkSkin: {0}, wSkinID: {1}, skTb.Count: {2}", okSkin,wSkinID,skTb.Count),NavTraceSwitch.Sw.Info);
				if (okSkin)
				{
					if ( NavTraceSwitch.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation SetPanelImageUrl skTb[wSkinID] : {0}", skTb[wSkinID]),NavTraceSwitch.Sw.Info);
					mn.ImageUrl         =   (string)skTb[wSkinID];
					if ( NavTraceSwitch.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation SetPanelImageUrl mn.ImageUrl: {0}", mn.ImageUrl),NavTraceSwitch.Sw.Info);
				}
			}
			catch (Exception ex)
			{
				if ( NavTraceSwitch.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RadPanelMenuNavigation SetPanelImageUrl ex: {0}", ex),NavTraceSwitch.Sw.Info);
			}
		}

		/// <summary> 
		/// Add a Menu Tree Node if user in in the list of Authorized roles. 
		/// </summary> 
		/// <param name="tabIndex">Index of the tab</param> 
		/// <param name="myPage">Tab to add to the MenuTreeNodes collection</param> 
		protected virtual void AddMenuItem(PageStripDetails myPage) 
		{
			bool okRole			    =	PortalSecurity.IsUserInRoles(myPage.AuthorizedRoles);
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation AddMenuItem PageName: {0}, PageID: {1}, OkRole: {2}, Roles: {3}", 
					new object[] { myPage.PageName, myPage.PageID, okRole, myPage.AuthorizedRoles }),NavTraceSwitch.Sw.Info);
			if (okRole) 
			{
				RadPanelItem mn	    =	new RadPanelItem(myPage.PageKeyPhrase);
				if ( myPage.PageID == StStr.WelcomePageID ) // We track Welcome Page to Add the Portal Name
					mn.Text         =   string.Format("{0}<br />{1}",myPage.PageKeyPhrase,portalSettings.PortalName);
				mn.ToolTip          =   mn.Text;
				if (ShowImages) 
				{
					string wSkinID  =   myPage.PageImage.ToLower(CultureInfo.InvariantCulture);
					if (string.IsNullOrEmpty(wSkinID))
						wSkinID     =   strDefaultskin;
					SetPanelImageUrl(mn, wSkinID,false);
				}

				mn.Value		    =	myPage.PageID.ToString();
				if ( NavTraceSwitch.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation AddMenuItem PageName: {0}, PageID: {1}, PageImage: {2}", myPage.PageName,myPage.PageID,myPage.PageImage),NavTraceSwitch.Sw.Info);

				RecursePanelItem(myPage.Pages, mn,1);
				// Pages with Id not assigned and Pages without children are url's Tabs
				if ( NavTraceSwitch.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation AddMenuItem PageName: {0}, Items.Count : {1}", myPage.PageName,mn.Items.Count),NavTraceSwitch.Sw.Info);
				if ( ( myPage.PageID == StStr.PageIDNotAssigned) || (mn.Items.Count == 0) || (myPage.nbModules > 0 ) )
				{
					mn.NavigateUrl = MenuHelper.GiveMeUrl(myPage.PageKeyPhrase, myPage.PageID,myPage.Flags,UseTabNameInUrl);
					if ( NavTraceSwitch.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation AddMenuItem PageName: {0}, NavigateUrl : {1}", myPage.PageName,mn.NavigateUrl),NavTraceSwitch.Sw.Info);
				}
				//always expand first item
				if ( Items.Count == 0 )
					mn.Expanded     =   true;
				Items.Add(mn);
			} 
		} 
		
		/// <summary>
		/// Select all pages for level sent
		/// </summary>
		protected virtual RadPanelItem RecursePanelItem(PageStripDetailsList t,RadPanelItem mn,int level) 
		{ 
			if ( NavTraceSwitch.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation RecursePanelItem Count: {0}, level: {1}", t.Count,level ),NavTraceSwitch.Sw.Info);
			if (t.Count > 0) 
			{ 
				bool isForm                     =   (Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms );
				IAddonNiceUser    curUser       =   PortalSettings.CurrentUser;
				bool isAuthenticated            =   ( curUser != null ) ? !curUser.IsAnonymous : false;
				for (int c=0; c < t.Count; c++) 
				{ 
					PageStripDetails mySubTab   =   t[c];
					if ( NavTraceSwitch.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation RecursePanelItem mySubTab.PageName: {0}, PageID: {1}, mySubTab.OkForMenus: {2}, mySubTab.AuthorizedRoles: {3}", 
							new object[]{mySubTab.PageName, mySubTab.PageID,mySubTab.OkForMenus,mySubTab.AuthorizedRoles} ),NavTraceSwitch.Sw.Info);
					if ( mySubTab.OkForMenus &&
					( isForm || ( !isForm && !mySubTab.FormsOnly ) ) &&
					( isAuthenticated || ( !isAuthenticated && !mySubTab.AuthenticatedOnly ) ) &&
						PortalSecurity.IsUserInRoles(mySubTab.AuthorizedRoles)) 
					{
						RadPanelItem mnc        =	new RadPanelItem(mySubTab.PageKeyPhrase);
						mnc.ToolTip             =   mnc.Text;
						mnc.Value		        =	mySubTab.PageID.ToString();
						RecursePanelItem(mySubTab.Pages, mnc,level+1);
						if ( NavTraceSwitch.Sw.TraceVerbose )
							Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation RecursePanelItem PageName: {0}, Items.Count : {1}", mySubTab.PageName,mnc.Items.Count),NavTraceSwitch.Sw.Info);
						if (( mnc.Items.Count == 0) || (mySubTab.nbModules > 0 ) )
						{
							mnc.NavigateUrl		=	MenuHelper.GiveMeUrl(mySubTab.PageKeyPhrase, mySubTab.PageID,mySubTab.Flags,UseTabNameInUrl);
							// We select the current page
							if ( mySubTab.PageID == portalSettings.ActivePageSettings.PageID )
								mnc.Selected    =   true;
							if ( NavTraceSwitch.Sw.TraceVerbose )
								Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation RecursePanelItem PageName: {0}, NavigateUrl : {1}", mySubTab.PageName,mnc.NavigateUrl),NavTraceSwitch.Sw.Info);
						}
						if ( ShowImages && (!FirstImagesOnly || (ImageOnParents && (mnc.Items.Count > 0))) )
						{
							string wSkinID      =   mySubTab.PageImage.ToLower(CultureInfo.InvariantCulture);
							if (string.IsNullOrEmpty(wSkinID))
								wSkinID         =   strDefaultskin;
							SetPanelImageUrl(mnc, wSkinID,true);
						}
					   mn.Items.Add(mnc);
					} 
				} 
			} 
			return mn; 
		}

		protected override void OnPreRender(EventArgs e)
		{
			if (WebControlsTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadPanelMenuNavigation OnPreRender BEG IsPostBack: {0}, Visible: {1}", Page.IsPostBack,Visible), WebControlsTraceSwitch.Sw.Info);

			// attaching the OnClientMouseOver/OnClientMouseOut javascript to onclick for the div
			if ( TrackClientMouse && !DesignMode )
			{
				((ADNPage)Page).RegisterStatusScript();
			}
			base.OnPreRender(e);
			if (WebControlsTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine("[V]RadPanelMenuNavigation OnPreRender END.", WebControlsTraceSwitch.Sw.Info);
		}
	} 
}